# _*_ coding:utf-8 _*_
# @Time:2020/11/11 22:56
# @Author:Cassie·Lau
# @File public_service.py

import os

from app.core.db.database import db
from app.core.error.code_total import StatusCode
from app.core.sql_compilations import SQLCompilations
from app.core.base_response import UnicornException
from app.config.settings import SUPPORT_FILES, RESOURCE_PATH
from app.utils.tools import Tools
from app.utils.parse import Parse


async def parse_upload_file(file, is_write=True):

    filename, suffix = Parse.file2name_suffix(file.filename)

    dirname = Parse.verify_dir(suffix,SUPPORT_FILES)

    if dirname:
        re_path = os.path.join(RESOURCE_PATH, dirname)
        u_name = Tools.uuid_name(filename)+suffix
        full_path = os.path.join(re_path, u_name)

        resource_id = Tools.uid()
        file_data = await file.read()
        with open(full_path, 'wb') as f:
            f.write(file_data)

        # 获取文件大小
        size = os.path.getsize(full_path)
        if is_write:
            db.insert(SQLCompilations.Resource.CREATE, resource_id, filename,full_path, size, suffix)

        return {
            "id": resource_id,
            "path": full_path,
            "filename": filename+suffix,
            "size": size,
        }

    else:
        raise UnicornException(StatusCode.R20003["code"], filename + StatusCode.R20003["msg"])


async def upload_one(file):
    return await parse_upload_file(file)


async def upload_more(files):
    resource_list = [await parse_upload_file(item, is_write=False) for item in files]
    if resource_list:
        s_tuple = [
            (data['id'], data['filename'], data['size'], data['file_suffix'], data['path'],) for data in resource_list
        ]
        db.insert_many(SQLCompilations.Resource.CREATE, s_tuple)
    return 0
